import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { MccModel } from './translator'
import { Meeting } from '@/api/manager/meeting'
import shallow from 'zustand/shallow'
import { getItemByMtKey, getItemInTree, getParentByChildMtKey } from './utils'
import { IStatusIcon } from '@/pages/manager/components'
import { IMcc } from '@/api/manager/type'
type StateStore = {
	tree: MccModel<Meeting>
	itemTotalStatus: IStatusIcon['totalStatus']
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	getMtModel: (mtKeys: (string | undefined)[]) => (MccModel<IMcc> | undefined)[]
	delMts: (mtKeys: string[]) => void
}
const initialState: StateStore = {
	tree: {
		mcc: { status: {} } as unknown as Meeting,
		status: {
			isOpen: false,
			isChecked: false,
			isMatchSearch: false,
			isCalling: false,
		},
		attr: {
			weightExceptVipInSortType2: 0,
		},
		nestingLevel: 0,
		mtKey: '',
		children: [],
	},
	itemTotalStatus: {
		vmp: false,
		mix: false,
		poll: false,
		dcs: false,
	},
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		getMtModel: (mtKeys) => {
			let tree = get().tree
			let treeMap: { [mtKey: string]: MccModel<IMcc> } = {}
			getItemInTree(tree, (item) => {
				treeMap[item.mtKey] = item
			})
			return mtKeys.map((x) => (x ? treeMap[x] : undefined))
		},
		delMts: (mtKeys) => {
			let tree = get().tree
			for (let index = 0; index < mtKeys.length; index++) {
				const mtKey = mtKeys[index]
				let item = getItemByMtKey(tree, mtKey)
				if (item) {
					if (item.mcc.mtType === 8) {
						//删除了上级会议
						let currentMeeting = getItemByMtKey(tree, '0.0.0.0_0') as MccModel<Meeting>
						if (currentMeeting) {
							currentMeeting.mcc.parentId = '0'
						}
						tree = currentMeeting
					} else {
						let parent = getParentByChildMtKey(tree, mtKey)
						if (parent) {
							parent.children = parent.children.filter((x) => x.mtKey !== mtKey)
						}
					}
				}
			}
			set({ tree: { ...tree } })
		},
	}))
)
export const useTableAllStore = create(store)
useTableAllStore.subscribe(
	(state) => {
		const tree = state.tree
		let vmp = false,
			mix = false,
			poll = false,
			dcs = false
		getItemInTree(tree, (item) => {
			if (item.mcc.status.isVmp) {
				vmp = true
			}
			if (item.mcc.isMt && item.mcc.status.isMix) {
				mix = true
			}
			if (item.mcc.isMt && item.mcc.status.isPoll) {
				poll = true
			}
			if (item.mcc.isMt && item.mcc.status.isDcs) {
				dcs = true
			}
		})
		return { vmp, mix, poll, dcs }
	},
	(cur) => {
		useTableAllStore.setState({
			itemTotalStatus: cur,
		})
	},
	{
		equalityFn: shallow,
	}
)
